#!/bin/bash

##########################################################################
#	Plotter - script to plot graphs of various generic test results
#
#	@author: Danilo Vasconcellos Vargas
##########################################################################

image_name="plot.png"
plot_settings=plot

#printing usage description
function USAGE ()
{
	echo ""
	echo "USAGE: "
	echo "  `basename $0` [-x lower_limit:higher_limit] [-y lower_limit:higher_limit] [-h] number_of_tests column1 column2 program_to_be_executed"
	echo ""
	echo "OPTIONS:"
	echo "  -x  pass a limit for the x coordinate"
	echo "  -y  pass a limit for the y coordinate"
	echo "  -h/--help  this usage information"
	echo "	-t  tittle"
	echo "  -i  save the image with the passed name"
	echo ""
	echo "EXAMPLE:"
	echo "  `basename $0` -x :19 10 15 14 foo"
	echo ""
	echo "This example compute 10 tests of the program called \"foo\" and plots the graph of the 15 column in the x coordinate"
	echo "the 14 column in the y coordinate and use as a higher limit for x the value 19"
	echo ""
	exit $E_OPTERROR    # Exit and explain usage, if no argument(s) given.
}

#getting options
while getopts ":x:y:ht:i:-:" Option
do
	case $Option in
		x)
			x1=`echo $OPTARG | cut -d ':' -f 1`;
			x2=`echo $OPTARG | cut -d ':' -f 2`;
			#echo "using x limits: $x1 and $x2"
		;; 
		
		y)
			y1=`echo $OPTARG | cut -d ':' -f 1`
			y2=`echo $OPTARG | cut -d ':' -f 2`
			#echo "using y limits: $y1 and $y2"
		;; 

		t)
			title=$OPTARG
		;;
		
		i)
			image_name=$OPTARG
		;;
		
		h)
			USAGE
		;;

		-)
			case $OPTARG in
			help)
				USAGE
			;;
			esac

		;;
		
		\?)
			echo "invalid option: -$OPTARG"
		;;
		
		*)
			echo "invalid option: -$OPTARG"
		;;
		

	#	:)
	#		echo "Wrong Parameters"
	#	exit
	#	;;
	 
	esac
done
shift $(($OPTIND - 1))

#checking if the remaining arguments meet the requirement
if [ $# -le 3 ]
then
	echo "error: not enough arguments"
	echo $@
	USAGE
	exit 
fi

number_of_files=$1
column1=$2
column2=$3
program=$4

#creating data from algorithm
for ((  i = 0 ;  i < $number_of_files ; i++  ))
do
	$program > $i.data
	sleep 1
done

#default setting for the plot
cat <<. > $plot_settings
#!/usr/bin/gnuplot
reset
set terminal png
set style data lines
set title $title
.

#case for just one test
if [ $number_of_files -eq 1 ]
then

	echo "plot [$x1:$x2][$y1:$y2] \"0.data\" using $column1:$column2 title \"data0\"" >> $plot_settings
	chmod +x $plot_settings
	`$plot_settings > $image_name`
	xv $image_name
exit
fi

#case for more than one test
echo "plot [$x1:$x2][$y1:$y2] \"0.data\" using $column1:$column2 title \"data0\", \\" >> $plot_settings
for (( i = 1 ; i < $number_of_files -1  ; i++ ))
do
	echo "\"$i.data\" using $column1:$column2 title \"data$i\", \\" >> $plot_settings
done
echo "\"$i.data\" using $column1:$column2 title \"data$i\"" >> $plot_settings

chmod +x $plot_settings
`$plot_settings > $image_name`
xv $image_name
exit
